// pages/invite/index.js
let canvas = null
let width = 0
let height = 0
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		loading: true
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		this.drawPosters()
	},
	/**
	 * 绘制海报
	 */
	async drawPosters() {
		try {
			const ctxDom = await this.selectorQuery('#poster')
			canvas = ctxDom[0].node
			const ctx = canvas.getContext('2d')
			const dpr = wx.getSystemInfoSync().pixelRatio
			width = ctxDom[0].width * dpr
			height = ctxDom[0].height * dpr
			canvas.width = width
			canvas.height = height
			// 背景
			const bgPath = '/static/my/shareBg.png'
			const bgImg = await this.loadImage(canvas, bgPath)
			console.log(bgImg);
			ctx.drawImage(bgImg, 0, 0, width, height)
			// 二维码
			const qrCodePath = await this.getUserQrCode()
			console.log(qrCodePath);
			const qrCodeImg = await this.loadImage(canvas, qrCodePath)
			const qrCodeWidth = 476 / 750 * width
			ctx.drawImage(qrCodeImg, width / 2 - qrCodeWidth / 2, 730 / 750 * width, qrCodeWidth, qrCodeWidth)
			this.setData({
				loading: false
			})
		} catch (err) {
			console.error(`[GM]：`, err);
		}
	},
	/**
	 * 保存海报
	 */
	savePoster() {
		wx.canvasToTempFilePath({
			canvas: canvas,
			destWidth: width,
			destHeight: height,
		}).then(res => {
			return wx.saveImageToPhotosAlbum({
				filePath: res.tempFilePath,
			})
		}).then(res => {
			wx.showToast({
				title: '保存成功',
				icon: "success"
			})
		}).catch(err => {
			console.error(`[GM]：`, err);
		})
	},
	// 获取太阳码
	getUserQrCode() {
		return new Promise((resolve, reject) => {
			wx.http.post(wx.api.UserQrCode, {
				url: `pages/index/index`
			}).then(res => {
				const {
					path
				} = res.data
				resolve(`${wx.api.host}/${path}`)
			})
		})
	},
	/**
	 * 获取画布上下文
	 * @param {*} elem css 选择器
	 */
	selectorQuery(elem) {
		return new Promise(function (resolve, reject) {
			const query = wx.createSelectorQuery()
			query.select(elem).fields({
				node: true,
				size: true
			}).exec((res) => resolve(res))
		})
	},
	/**
	 * 下载图片
	 */
	getDownload(url) {
		return new Promise(function (resolve, reject) {
			wx.downloadFile({
				url,
				success: res => resolve(res),
				fail: err => reject(err)
			})
		})
	},
	/**
	 * 加载图片
	 * @param {*} canvas 
	 * @param {*} src 
	 */
	loadImage(canvas, src) {
		return new Promise(function (resolve, reject) {
			const img = canvas.createImage()
			img.src = src
			img.onload = () => resolve(img)
		})
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {

	}
})